import 'dart:async';
import 'dart:io';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path_provider/path_provider.dart';

class CacheUtil {
  static const key = 'romkoCacheKey';
  static Stream<FileResponse>? _fileSteam;
  static StreamSubscription? _listener;

  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(minutes: 1),
      maxNrOfCacheObjects: 100,
      repo: JsonCacheInfoRepository(databaseName: key),
      fileService: HttpFileService(),
    ),
  );

  //缓存文件到本地
  static cacheFileToLocal(String url) {
    _fileSteam = instance.getFileStream(url, withProgress: true);
    _listener = _fileSteam?.listen((event) {
    });
    _listener?.onData((data) {

    });
  }

  //暂停缓存
  static cancelCache(String url) {
    instance.removeFile(key);
    _listener?.cancel();
  }

  //获取缓存文件
  static Future<FileInfo?> getCacheFile(String url) async {
    return await instance.getFileFromCache(url);
  }

  /// 获取缓存大小
  static Future<String> total() async {
    Directory tempDir = await getTemporaryDirectory();
    int total = await _reduce(tempDir);
    final size = formatSize(double.parse(total.toString()));
    return size;
  }

  static Future<String> formatSize(double value) async {
    if (value == 0) return '';
    List<String> unitArr = []
    // ignore: prefer_inlined_adds
      ..add('B')
      ..add('K')
      ..add('M')
      ..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];

  }


  /// 清除缓存
  static Future<void> clear() async {
    Directory tempDir = await getTemporaryDirectory();
    // ignore: unnecessary_null_comparison
    if (tempDir == null) return;
    await _delete(tempDir);
  }

  /// 递归缓存目录，计算缓存大小
  static Future<int> _reduce(final FileSystemEntity file) async {
    /// 如果是一个文件，则直接返回文件大小
    if (file is File) {
      int length = await file.length();
      return length;
    }
    /// 如果是目录，则遍历目录并累计大小
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      int total = 0;
      if (children.isNotEmpty) {
        for (FileSystemEntity child in children) {
          total += await _reduce(child);
        }
      }
      return total;
    }
    return 0;
  }

  /// 递归删除缓存目录和文件
  static Future<void> _delete(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await _delete(child);
      }
    } else {
      await file.delete();
    }
  }
}